//
//  ZZMainNewsTableView.m
//  ZZNews
//
//  Created by 周英培 on 16/7/27.
//  Copyright © 2016年 周英培. All rights reserved.
//

#define MainNewsTableViewCell @"MainNewsTableViewCell"

#import "ZZMainNewsTableView.h"
#import "ZZMainNewsTableViewCell.h"
#import "ZZMainNewsModel.h"
#import "AFNetworking.h"
@interface ZZMainNewsTableView ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic,strong) NSMutableArray *news;

@property (nonatomic,strong) UIActivityIndicatorView *activityIndicatorView;

// 加载更过数据开始的位置
@property (nonatomic,assign) NSInteger index;

@end

@implementation ZZMainNewsTableView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    
    if (self) {
        
        self.dataSource = self;
        
        self.delegate = self;
        
        self.separatorStyle = UITableViewCellSeparatorStyleNone;
        
    }
    
    return self;
}



- (void)setNewsChannelModel:(ZZNewsChannelModel *)newsChannelModel {

    _newsChannelModel = newsChannelModel;
    
    self.index = 10;
    
    //MARK:加载新的数据之前，清空数据源
    [self.news removeAllObjects];
    
    [self reloadData];
    
    [self.activityIndicatorView startAnimating];
    
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    
    //MARK:加载新闻主界面网络数据
    [self loadNewsMainServiceDataWithTid:newsChannelModel.tid];
    
}

/// 利用NSURLSection加载新闻主界面网络数据
- (void)loadNewsMainServiceDataWithTid:(NSString *)tid {
    
    NSString *urlString = [NSString stringWithFormat:@"http://c.m.163.com/nc/article/headline/%@/0-20.html",tid];
    
    NSURL *url = [NSURL URLWithString:urlString];

    [[[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
        
        NSMutableArray *dataArr = dict[tid];
        
        [dataArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
           
            NSDictionary *dict = obj;
            
            ZZMainNewsModel *mainNewsModel = [ZZMainNewsModel mainNewsModelWithDict:dict];
            
            [self.news addObject:mainNewsModel];
            
        }];
        
        //MARK:刷新数据
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self reloadData];
            
            [self.activityIndicatorView stopAnimating];
            
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
            
        });
        
        
    }] resume];

}

/// 利用AFN加载更多网络数据
- (void)loadMoreDataWithStartIndex:(NSInteger)index {

    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    
    NSString *urlString = [NSString stringWithFormat:@"http://c.m.163.com/nc/article/headline/%@/%zd-10.html",self.newsChannelModel.tid,index];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    [manager GET:urlString parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *dict = responseObject;
        
        NSArray *newArr = dict[self.newsChannelModel.tid];
        
        [newArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            NSDictionary *dict = obj;
            
            ZZMainNewsModel *mainNewsModel = [ZZMainNewsModel mainNewsModelWithDict:dict];
            
            [self.news addObject:mainNewsModel];
            
        }];
        
        dispatch_async(dispatch_get_main_queue(), ^{
           
            [self reloadData];
            
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
            
        });
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"error:%@",error);
        
    }];

}

#pragma mark - UITableViewDatasouce
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.news.count;

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    //MARK:从加载更多数据的位置加载数据
    if (self.index == indexPath.row) {
        
        self.index += 10;
        
        [self loadMoreDataWithStartIndex:self.index];
        
    }

    ZZMainNewsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MainNewsTableViewCell];
    
    if (!cell) {
        
        cell = [[ZZMainNewsTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MainNewsTableViewCell];
        
        //取消cell的选中状态
//        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
    }
    
    ZZMainNewsModel *mainNewsModel = self.news[indexPath.row];
    
    cell.mainNewsModel = mainNewsModel;
    
    return cell;

}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    return 80;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    [tableView deselectRowAtIndexPath:indexPath animated:YES];

}

#pragma mark - 懒加载
- (NSMutableArray *)news {

    if (!_news) {
        
        _news = [NSMutableArray array];
        
    }

    return _news;
    
}

- (UIActivityIndicatorView *)activityIndicatorView {

    if (!_activityIndicatorView) {
        
        _activityIndicatorView = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
        
        _activityIndicatorView.center = self.center;
        
        _activityIndicatorView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
        
        [self addSubview:self.activityIndicatorView];
        
    }
    
    return _activityIndicatorView;

}

@end
